package com.jsmtr.rms.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.IConfigService;
import com.jsmtr.rms.utils.FilePathUtil;
import com.jsmtr.rms.utils.StringTools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.entity.vo.CMSNodeForm;
import com.jsmtr.rms.service.ICMSService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.DateTools;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping("/CMS")
public class CMSController {

    @Resource
    private IUtilService utilService;

    @Resource
    private ICMSService cmsService;

    @Resource
    private IConfigService configService;

    //首页
    @RequestMapping("/index")
    public String Index(HttpServletRequest request, Model model) {
        try {
            List<CMSNode> nodes = cmsService.getNodes();
            StringBuilder str = new StringBuilder();
            for (CMSNode node : nodes) {
                str.append("<option value='" + node.getId() + "'>" + node.getNodename() + "</option>");
            }
            model.addAttribute("nodes", str);

            //获取前端根目录地址
            List<BaseConfig> sysConfigs = configService.getConfigs("sys");
            String path = "";
            for (BaseConfig sysConfig : sysConfigs) {
                if (sysConfig.getCode().equals("path")){
                    path = sysConfig.getCont();
                }
            }
            model.addAttribute("path", path);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/cms/index";
    }

    //获得文章信息
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getlists", method = RequestMethod.POST)
    public void GetList(HttpServletRequest request, HttpServletResponse response, CMSContent cont) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));

            Map<String, Object> map = cmsService.getResults(page, perpage, cont);

            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (CMSContent content : (List<CMSContent>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id=\"cb_" + content.getId() + "\" /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + content.getNodename() + "</td>");
                    result.append("<td>" + content.getCmstype() + "</td>");
                    result.append("<td>" + content.getTitle() + "</td>");
                    result.append("<td>" + DateTools.toLenStr(content.getAddtime()) + "</td>");
                    result.append("<td>" + content.getAdduname() + "</td>");
                    result.append("<td>" + content.getIsdis() + "</td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='6'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    //添加文章
    @RequestMapping("/add")
    public String Add(HttpServletRequest request, Model model) {
        try {
            List<CMSNode> nodes = cmsService.getNodes();
            StringBuilder str = new StringBuilder();
            for (CMSNode node : nodes) {
                str.append("<option value='" + node.getId() + "'>" + node.getNodename() + "</option>");
            }
            model.addAttribute("nodes", str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/cms/add";
    }

    @Autowired
    private FilePathUtil filePathUtil;

    @RequestMapping("/uploadpic")
    public void uploadpic(@RequestBody(required = true) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        try {

            String ipath = filePathUtil.getImgpath();
            String mpath = filePathUtil.getMappath();
            File dir = new File(mpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            UUID uuid = UUID.randomUUID();
            String newFile = mpath + File.separator + uuid.toString();
            File nfile = new File(newFile);
            if (!nfile.exists()) {
                nfile.createNewFile();
            }
            file.transferTo(nfile);
            response.getWriter().write(request.getScheme() + "://"+ request.getServerName() + ":"
                    + request.getServerPort() + ipath + "/" + uuid.toString());
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }


    //添加文章
    @RequestMapping(value = "/AddAction", method = RequestMethod.POST)
    public void AddAction(HttpServletRequest request, HttpServletResponse response, CMSContent cont) {
        try {
            if (request.getParameter("conts") != null) {
                BaseUser user = utilService.getSessionUser(request);
                cont.setId(UUID.randomUUID().toString());
                cont.setAdduid(user.getId());
                cont.setCont(request.getParameter("conts").getBytes());
                cont.setAdduname(user.getUname());
                cont.setNodename(cmsService.getNode(cont.getNodeid()).getNodename());
                utilService.addObject(cont);
                utilService.printJsonResult(true, "操作成功！", "/CMS/index", response);
            } else {
                utilService.printJsonResult(false, "文章内容不能为空！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //修改文章
    @RequestMapping("/edit")
    public String Edit(HttpServletRequest request, Model model) {
        try {
            List<CMSNode> nodes = cmsService.getNodes();
            StringBuilder str = new StringBuilder();
            for (CMSNode node : nodes) {
                str.append("<option value='" + node.getId() + "'>" + node.getNodename() + "</option>");
            }
            model.addAttribute("nodes", str);

            CMSContent content = cmsService.getContent(request.getParameter("id").trim());
            model.addAttribute("content", content);
            model.addAttribute("continfo", new String(content.getCont()));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/cms/edit";
    }

    //修改文章
    @RequestMapping(value = "/EditAction", method = RequestMethod.POST)
    public void EditAction(HttpServletRequest request, HttpServletResponse response, CMSContent cont) {
        try {
            if (request.getParameter("conts") != null) {
                CMSContent content = cmsService.getContent(cont.getId());
                content.setNodename(cmsService.getNode(cont.getNodeid()).getNodename());
                content.setTitle(cont.getTitle());
                content.setCont(request.getParameter("conts").getBytes());
                content.setIsdis(cont.getIsdis());
                content.setAddtime(cont.getAddtime());
                content.setCmstype(cont.getCmstype());
                utilService.editObject(content);
                utilService.printJsonResult(true, "操作成功！", "/CMS/index", response);
            } else {
                utilService.printJsonResult(false, "文章内容不能为空！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //删除文章
    @RequestMapping(value = "/DelAction", method = RequestMethod.POST)
    public void DelAction(HttpServletRequest request, HttpServletResponse response, CMSContent cont) {
        try {
            String ids = request.getParameter("id");
            if (StringTools.trimNotEmpty(ids)){
                if (ids.indexOf(",")>0){
                    ids=ids.substring(0,ids.length()-1);
                }
                CMSContent cmsContent=  cmsService.getContent(ids);
                if (!cmsContent.getIsdis().equalsIgnoreCase("正常")){
                    utilService.delObject(cmsContent);
                    utilService.printJsonResult(true, "操作成功！", "no", response);
                }else{
                    utilService.printJsonResult(false, "操作失败！仅已保存或已下线文章可以删除！", "no", response);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //栏目管理
    @RequestMapping("/node")
    public String Node(HttpServletRequest request, Model model) {
        try {
            StringBuilder str = new StringBuilder();
            List<CMSNode> nodes = cmsService.getNodes();
            int num = 0;
            for (CMSNode node : nodes) {
                str.append("<tr><td><div><input type='text' name='node[" + num + "].ordernum' value='" + node.getOrdernum() + "' datatype='*' nullmsg='栏目排序号不能为空！' />" +
                        "<input type='hidden' name='node[" + num + "].id' value='" + node.getId() + "' /></div></td>");
                str.append("<td><div><input type='text' name='node[" + num + "].nodename' value='" + node.getNodename() + "' datatype='*' nullmsg='栏目名称不能为空！' /></div></td>");
                str.append("<td><div><select name='node[" + num + "].state' datatype='*' nullmsg='显示到前台菜单不能为空！'>");
                str.append("<option value='0'>显示</option><option value='1'>不显示</option></select>");
                str.append("<input type='hidden' value='" + node.getState() + "' /></div></td>");
                str.append("<td><div><select name='node[" + num + "].type' datatype='*' nullmsg='内容显示方式不能为空！'>");
                str.append("<option value='0'>默认</option><option value='1'>显示最新发布的一条信息</option></select>");
                str.append("<input type='hidden' value='" + node.getType() + "' /></div></td>");
               if (node.getDel() == 0) {
                    //str.append("<td><button type='button' class='del'></button></td></tr>");
                   str.append("<td class=\"tdwidth\"><button type=\"button\"  class=\"layui-btn layui-btn-sm layui-btn-normal del\"><i class=\"layui-icon\">\uE640</i> 删除</button></td>");
                }
               else {
                    str.append("<td class=\"tdwidth\">&nbsp;</td></tr>");
                }
                num++;
            }
            model.addAttribute("result", str);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("result", "");
        }
        return "/cms/node";
    }

    //栏目管理
    @SuppressWarnings({"unchecked", "rawtypes"})
    @RequestMapping(value = "/NodeAction", method = RequestMethod.POST)
    public void NodeAction(HttpServletRequest request, HttpServletResponse response, CMSNodeForm form) {
        try {
            List addList = new ArrayList();
            List editList = new ArrayList();
            List<CMSNode> nodes = form.getNode();
            for (CMSNode node : nodes) {
                if (node.getId() == null || node.getId().trim().length() == 0) {
                    node.setId(UUID.randomUUID().toString());
                    node.setDel(0);
                    addList.add(node);
                } else {
                    CMSNode _node = cmsService.getNode(node.getId());
                    _node.setNodename(node.getNodename());
                    _node.setState(node.getState());
                    _node.setType(node.getType());
                    _node.setOrdernum(node.getOrdernum());

                    editList.add(_node);

                    //修改内容栏目名称
                    List<CMSContent> conts = cmsService.getContents(node.getId());
                    for (CMSContent cont : conts) {
                        cont.setNodename(node.getNodename());
                    }
                    editList.addAll(conts);
                }
            }

            utilService.editList(editList, addList);
            utilService.printJsonResult(true, "操作成功！", "no", response);

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //删除栏目&内容
    @SuppressWarnings({"unchecked", "rawtypes"})
    @RequestMapping(value = "/DelNodeAction", method = RequestMethod.POST)
    public void DelNodeAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            List list = new ArrayList();
            list.add(cmsService.getNode(id));
            list.addAll(cmsService.getContents(id));

            utilService.delList(list);
            utilService.printJsonResult(true, "成功删除栏目及内容！", "no", response);

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }


    @RequestMapping(value = "/PublishCMS")
    public void pubCmsContent(HttpServletRequest request,HttpServletResponse response){
        try {
            String ids = request.getParameter("id");
            if (StringTools.trimNotEmpty(ids)){
                if (ids.indexOf(",")>0){
                    ids=ids.substring(0,ids.length()-1);
                }
                CMSContent cmsContent=  cmsService.getContent(ids);
                cmsContent.setIsdis("正常");
                utilService.editObject(cmsContent);
                utilService.printJsonResult(true, "操作成功！", "no", response);
            }else{
                utilService.printJsonResult(false, "请选择要发布的文章！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    @RequestMapping(value = "/DownCMS")
    public void downCmsContent(HttpServletRequest request,HttpServletResponse response){
        try {
            String ids = request.getParameter("id");
            if (StringTools.trimNotEmpty(ids)){
                if (ids.indexOf(",")>0){
                    ids=ids.substring(0,ids.length()-1);
                }
              CMSContent cmsContent=  cmsService.getContent(ids);
                cmsContent.setIsdis("已下线");
                utilService.editObject(cmsContent);
                utilService.printJsonResult(true, "操作成功！", "no", response);
            }else{
                utilService.printJsonResult(false, "请选择要下线的文章！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //详细内容页
    @RequestMapping(value = "/Preview")
    public String Preview(HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String id = request.getParameter("id").trim();
            if (!StringTools.trimNotEmpty(id)){
                utilService.printJsonResult(false, "请选择要预览的文章！", "no", response);
            }
            if(id.indexOf(",")>0){
                id=id.substring(0,id.length()-1);
            }
            CMSContent cont = cmsService.getContent(id);
            CMSNode node = cmsService.getNode(cont.getNodeid());
            if (node.getState() == 0) {
                model.addAttribute("nodename", node.getNodename());
                StringBuilder result = new StringBuilder();
                result.append("<div class='ctitle'>" + cont.getTitle() + "</div>");
                result.append("<div class='ctime'>发布时间：" + DateTools.toDayStr(cont.getAddtime()) + "</div>");
                result.append("<div class='cdetail'>" + new String(cont.getCont()) + "</div>");
                model.addAttribute("detail", result);
                String servletpath=request.getServletPath();
                String loginType="";
                if(servletpath.indexOf("/GX/")>=0){
                    loginType="GX";
                }else if(servletpath.indexOf("/ZGZ/")>=0){
                    loginType="ZGZ";
                }else if(servletpath.indexOf("/SZ/")>=0){
                    loginType="SZ";
                }
                model.addAttribute("logintype",loginType);
            } else {
                utilService.printJsonResult(false, "操作失败！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/cms/preview";
    }

    //文章
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getlistsLayuiJson", method = RequestMethod.GET)
    public LayuiDataTableResultBean getCMsLayuiJson(HttpServletRequest request, HttpServletResponse response, CMSContent cont) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            Map<String, Object> map = cmsService.getResults(page, limit, cont);

            double pageCount = (Double) map.get("pageCount");

            JSONArray jsonArray = new JSONArray();

            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (CMSContent content : (List<CMSContent>) object) {
                    JSONObject jsonObject = JSONObject.fromObject(content);
                    jsonObject.put("ids","cb_" + content.getId());
                    jsonObject.put("id",limit * (page-1) + num);
                    jsonObject.put("addtime",DateTools.toLenStr(content.getAddtime()));
                    jsonArray.add(jsonObject);
                    num++;
                }
            } else {

            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double)map.get("count")).intValue());
            result.setData(jsonArray);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }

    }
}
